package tianrun.ziguan.api.calculate.config.service.common.edit;

import com.google.common.collect.Sets;
import org.apache.shiro.util.Assert;
import org.springframework.stereotype.Service;
import tianrun.ziguan.api.calculate.config.dto.request.StaticPropertiesInstanceVO;
import tianrun.ziguan.api.calculate.config.dto.request.common.DeleteBody;
import tianrun.ziguan.api.calculate.config.dto.request.common.add.edit.SaveBody;
import tianrun.ziguan.api.calculate.config.service.ge.TGeTableConfigService;
import tianrun.ziguan.api.calculate.config.service.template.instance.ITStaticPropertiesInstanceService;
import tianrun.ziguan.api.calculate.config.utils.MapUtil;
import tianrun.ziguan.api.calculate.config.utils.StringUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class StaticPropertiesInstanceDealService extends AbstractDealService {

    private final ITStaticPropertiesInstanceService staticPropertiesInstanceService;

    public StaticPropertiesInstanceDealService(TGeTableConfigService tableConfigService,
                                               ITStaticPropertiesInstanceService staticPropertiesInstanceService) {
        super(tableConfigService);
        this.staticPropertiesInstanceService = staticPropertiesInstanceService;
    }

    @Override
    public void before(SaveBody body) {
        Long templateId = MapUtil.getLong(body.getRawData(), "template_id");
        String label = MapUtil.getString(body.getData(), "label");
        if (StringUtil.isEmpty(label))return;
        Assert.isTrue(Objects.nonNull(templateId),label+"：模板id不能为空");
        List<StaticPropertiesInstanceVO> vos = staticPropertiesInstanceService.listVOByTemplateIds(Sets.newHashSet(templateId));
        if (vos.isEmpty())return;
        long count;
        if (Objects.equals(body.getOption(), SaveBody.Option.EDIT)) {
            count = vos.stream()
                    .filter(vo -> (!Objects.equals(vo.getId(),body.getId())) && Objects.equals(vo.getLabel(), label))
                    .count();
        } else {
            count = vos.stream()
                    .filter(vo -> Objects.equals(vo.getLabel(), label))
                    .count();
        }
        Assert.isTrue(count == 0,
                "组件中实例点位" + label + "已存在！");
    }


    @Override
    public String tableName() {
        return "t_static_properties_instance";
    }

    @Override
    public void after(SaveBody body) {
    }

    @Override
    public void delBefore(DeleteBody body) {

    }

    @Override
    public void listAfter(List<Map<String, Object>> result) {

    }

    @Override
    public void delAfter(DeleteBody body) {

    }

    @Override
    public void infoAfter(Map<String, Object> bean) {

    }


}
